import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { redirectToAdapter } from '@/base/http/utils';
import { fetchCreatePayment } from '@/business/services/trade/payment/payment';
import { createOrder } from '@/business/services/payment/order';

/**
 * @description 支付状态管理
 * @author Shawn
 * @date 2024-7-13
 */

type Actions = {
  // 创建支付
  createPayment: (payName: string, price: string, id: string) => boolean;
  // 微信支付
  wechatPay: (paymentRequest: PaymentRequest, orderId: string) => Promise<boolean>;
  // 支付回调
  payCallback: (orderNo: string, paySuccess: boolean) => Promise<boolean>;
};

export const paymentStore = create<Actions>()(
  immer(() => ({
    /**
     * 创建支付单
     * @param orderNo 订单号
     * @param payMethod 支付方式
     * @param orderType 订单类型
     * @param id 微信授权ID
     */
    createPayment: async (payName: string, price: string, id: string) => {
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const requestData = {
          payName,
          price,
          id,
        };
        const res = await createOrder(requestData);
        const actions = paymentStore.getState();
        // if (!payed && paymentRequest) {
        //   // 如果未支付，调用微信支付
        const res1 = await actions.wechatPay(res.data, res.orderId);
        return res1
      } catch (error) {
        console.log('创建支付失败', error);
      } finally {
        Taro.hideLoading();
      }
    },

    /**
     * 微信支付
     * @param paymentRequest 支付请求
     * @param orderCode 订单号
     * @param orderType 订单类型
     */
    wechatPay: (paymentRequest: PaymentRequest, orderId: string) => {
      return new Promise((resolve, reject) => {
        try {
          const actions = paymentStore.getState();

          Taro.requestPayment({
            ...paymentRequest,
            success: async () => {
              await actions.payCallback(orderId, true);
              resolve(true);
            },
            fail: async (error) => {
              console.log('微信支付异常', error);
              await actions.payCallback(orderId, false);
              resolve(false);
            },
          } as Taro.requestPayment.Option);
        } catch (error) {
          reject(error);
        }
      });
    },

    /**
     * 支付回调
     * @param orderNo 订单号
     * @param paySuccess 是否支付成功
     * @param orderType 订单类型
     */
    payCallback: async (orderNo: string, paySuccess: boolean) => {
      return new Promise((resolve, reject) => {
        try {
          Taro.showToast({
            title: paySuccess ? '支付成功' : '支付取消',
            icon: paySuccess ? 'success' : 'error',
            duration: 1000,
          });

          // 支付回调成功后跳转到付款成功页面
          // setTimeout(() => {
          //   if (paySuccess) {
          //     redirectToAdapter({
          //       url: `/pages/payment/paymentSuccess/index?orderNo=${orderNo}&orderType=${orderType}`,
          //     });
          //   }
          // }, 1000);
          if (paySuccess) {
            resolve(true);
          }
          resolve(false);
        } catch (error) {
          reject(error);
        }
      });
    },
  })),
);
